package MydbQA::Command::Tables;

use strict;
use warnings;

use base 'MydbQA::Command::Base';

use Carp;
use Getopt::Long;
use Storable qw (dclone);

use MySQL::Describe;
use MySQL::Query::Performance;
use MySQL::Query::Performance::Count;
use MySQL::Query::Performance::GroupBy;

use HTML::Template;
use List::Util qw(min max sum);

sub run {
      my $self = shift;
      
      $self->extract_and_count;
      $self->describe_tables;
      
      $self->{html} ? $self->as_html : $self->as_text;
}

sub describe_tables {
      my ($self) = @_;
      
      my $describe = MySQL::Describe->new(dbh => $self->dbh);
      my $tables_list = $self->tables->tables;
      foreach my $table (@$tables_list) {
            $describe->describe($table);
            my %temp = ();
            $temp{describe_t} = $table;
            $temp{describe_t_res} = $describe->results;
            push @{$self->{_data}->{describe}} , \%temp;
      }
}

sub extract_and_count {
      my ($self) = @_;
      
      my $tables_list = $self->tables->tables;
      my $aliases_list = $self->tables->aliases;
     
      my $uniq = $self->tables->uniq;
      foreach my $u (@$uniq) {
            my %temp;
            
            my $builder = $self->extract->extract_one($u);
            my $count = MySQL::Query::Performance::Count->new();
            my $count_sql = $count->create_count_sql($builder); 
            
            my $sth = $self->dbh->prepare($count_sql->sql);
            $sth->execute();
            my $value = $sth->fetchrow_arrayref();
            
            $temp{'extract_q'} = $builder->sql;
            $temp{'extract_c_res'} = $value->[0];
            $temp{'extract_c_sql'} = $count_sql->sql;
            
            push @{$self->{_data}->{extract}} , \%temp;  
      }
}

sub as_html {
      my ($self , $data) = @_;
        
      my $tmpl = HTML::Template->new( filename => "../share/tmpl/tables.html" , die_on_bad_params => 0 );
      $tmpl->param(extract => $self->{_data}->{extract});
      $tmpl->param(describe => $self->{_data}->{describe});
      $tmpl->param(nohighlight => 1) if $self->{nohighlight};
      
      my $path = $self->{output};
      
      open (FH , "+>$path/analyze_tables.html") || die print $!;
            print FH $tmpl->output;
      close FH;
        
      print "Tables report generated in html file: $path/analyze_tables.html\n"; 
}

sub as_text {
      print "Text report is not implemented yet";
}

1;
